'use strict';
/**
 * @author 张少辉
 * 创建时间：2015-11-23 09:08:47
 * 创建任务号：无
 * 创建原因：添加页面安全认证,防止未登录跳转到其他页面
 */
angular.module('nec-admin.common')
    .provider('authService', function() {
        var isOpenAuth = true;

        this.setAuthStatus = function(isAuth) {
            isOpenAuth = isAuth;
        };

        this.$get = ['$rootScope', '$state', '$resource', '$q', 'tokenService', '_',
            function($rootScope, $state, $resource, $q, tokenService, _) {
                var authenticated = false; //是否已验证

                var auth = {
                    loginState: 'login', //登录状态

                    /**
                     * 设置验证服务的用户名和密码，并保存token
                     * @param {String} 用户名
                     * @param {String} 密码
                     * @return Promise
                     */
                    authenticate: function(username, password) {
                        authenticated = true;
                        if (isOpenAuth) {
                            tokenService.setToken(username, password);
                        }
                        return $q.resolve(true);
                    },

                    /**
                     * 注销
                     * @return {[Promise]}
                     */
                    logout: function() {
                        authenticated = false;
                        tokenService.clearToken();
                        return $q.resolve(true);
                    },

                    /**
                     * 初始化验证,这里参数的状态都是排除的状态，无需验证就可以进入
                     * @param  {[String]} loginState 登录状态,这个也会被排除验证
                     * @param  {[Array]} exceptStates 排除状态集合
                     */
                    init: function(loginState, exceptStates) {
                        auth.loginState = loginState || auth.loginState;
                        auth.exceptStates = exceptStates || [];

                        $rootScope.$on('$stateChangeStart',
                            function(event, toState) {
                                enter(toState, event);
                            });
                        $rootScope.$on('$stateChangeError',
                            function(event, toState, toParams, fromState, fromParams, error) {
                                console.log('stateChangeError:', error);
                            });
                        $rootScope.$on('$stateNotFound',
                            function(event, unfoundState) {
                                console.log('stateNotFound:', unfoundState);
                            });
                    }

                };

                /**
                 * 进入页面验证事件
                 * @param  {[type]} state 要进入的页面状态
                 * @param  {[type]} event 进入页面的事件
                 * @return {[type]}       无
                 */
                function enter(state, event) {
                    if (isNeedAuthenticate(state) && isOpenAuth) {
                        if (!authenticated) {
                            $state.go(auth.loginState);
                            event.preventDefault();
                        }
                    }
                }
                /**
                 * 是否需要认证
                 * @param  {[Object:State]}  state 状态对象
                 * @return {Boolean}      是否需要验证
                 */
                function isNeedAuthenticate(state) {
                    auth.exceptStates.unshift(auth.loginState);
                    auth.exceptStates.unshift(true);
                    var isNeedAuthState = _.reduce(auth.exceptStates,
                        function(last, stateName) {
                            return last && state.name !== stateName;
                        });
                    return isNeedAuthState &&
                        !tokenService.getToken();
                }
                return auth;
            }
        ];
    })
    .run(['authService', function(authService) {
        authService.init();
    }]);
